package com.zaimokuza.cn.service.impl;

import com.zaimokuza.cn.entity.enums.CustomizeExceptionEnum;
import com.zaimokuza.cn.entity.follow.Follow;
import com.zaimokuza.cn.mapper.FollowMapper;
import com.zaimokuza.cn.service.FollowService;
import com.zaimokuza.cn.service.UserService;
import com.zaimokuza.cn.util.AssertUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author zaimokuza
 */
@Service
public class FollowServiceImpl implements FollowService {

    @Resource
    private UserService userService;
    @Resource
    private FollowMapper followMapper;

    @Override
    public void follow(String targetUserId, String userId) {
        // 整理关注信息
        Follow follow = new Follow(userId, targetUserId);
        // 校验关注关系是否存在
        Integer recordIsExist = followMapper.queryRecordIsExist(follow);
        AssertUtils.isNull(recordIsExist, CustomizeExceptionEnum.FOLLOW_REPEAT);
        // 添加记录
        followMapper.insertFollowRecord(follow);
        // 调整相应统计信息
        userService.increaseFollowers(targetUserId);
        userService.increaseFollowing(userId);
    }

    @Override
    public void unfollow(String targetUserId, String userId) {
        // 整理关注信息
        Follow follow = new Follow(userId, targetUserId);
        // 校验关注关系是否存在
        Integer recordIsExist = followMapper.queryRecordIsExist(follow);
        AssertUtils.notNull(recordIsExist, CustomizeExceptionEnum.UNFOLLOW_REPEAT);
        // 添加记录
        followMapper.deleteFollowRecord(follow);
        // 调整相应统计信息
        userService.reduceFollowers(targetUserId);
        userService.reduceFollowing(userId);
    }

}
